import formencode
import formencode.validators as validators
import urllib2, urllib


class ReCaptchaValidator(validators.FormValidator):
# Usage:     
#    recaptcha_challenge_field = forms.String()
#    recaptcha_response_field = forms.String()
#    chained_validators = [ReCaptchaValidator(recaptcha_challenge_field, recaptcha_response_field)]

    validate_partial_form = True

    challenge_field = 'recaptcha_challenge_field'
    response_field = 'recaptcha_response_field'
    recapture = 'recaptcha'
    __unpackargs__ = ('recaptcha_challenge_field', 'recaptcha_response_field')

    def validate_partial(self, field_dict, state):
        print "-------------1"
        if not field_dict.get(self.challenge_field, None) \
           or not field_dict.get(self.response_field, None):
            return None
        self.validate_python(field_dict, state)

    def validate_python(self, field_dict, state):
        print "-------------2"
        errors = self._validateReturn(field_dict, state)
        if errors:
            error_list = errors.items()
            error_list.sort()
            raise forms.Invalid(
                '<br>\n'.join(["%s: %s" % (name, value)
                               for name, value in error_list]), 
                field_dict, state, error_dict=errors)
        
    def _validateReturn(self, field_dict, state):
        challenge = field_dict[self.challenge_field]
        response = field_dict[self.response_field]
        print "-------------3"
        print challenge
        print response
        if not (response and challenge and
                len (response) and len (challenge)):
            return {self.recapture: 'incorrect-captcha-sol'}
        
        params = urllib.urlencode ({
            'privatekey': '6Lc8ngAAAAAAAKAKIN4S-QA9z2nPb4o7n-ES4uU9', 
            'remoteip' : state.remote_ip, 
            'challenge': challenge, 
            'response' : response, 
            })
    
        request = urllib2.Request (
            url = "http://%s/verify" % "api-verify.recaptcha.net", 
            data = params, 
            headers = {
                "Content-type": "application/x-www-form-urlencoded", 
                "User-agent": "reCAPTCHA Python"
                }
            )
        
        httpresp = urllib2.urlopen (request)
    
        return_values = httpresp.read ().splitlines ();
        httpresp.close();
    
        return_code = return_values [0]
    
        if (return_code == "true"):
            return None
        else:
            return {self.recapture: return_values [1]}


class Captha(validators.FancyValidator):

     messages = {
         'wrong_capthca': 'Wrong. Please try again', 
         }

     def _to_python(self, value, state):
         return value.strip()

     def validate_python(self, value, state):
         if value != state.captcha:
             raise formencode.api.Invalid(self.message("wrong_capthca", state), 
                           value, state)

class RegisterFormSchema(formencode.Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    username = validators.String(not_empty=True)
    email = validators.Email(not_empty=True)
    #Replase on SecurePassword see documentation
    password = validators.String(not_empty=True)
    password_confirm = validators.String(not_empty=True)
    captcha = Captha()
    chained_validators = [validators.FieldsMatch('password', 'password_confirm')]
    tos = validators.Bool()
#    chained_validators = [forms.FieldsMatch('password', 'password_confirm')]

class AddCommentFormSchema(formencode.Schema):
    allow_extra_fields = True
    filter_extra_fields = True
    text = validators.String(not_empty=True)
    author_name = validators.String(not_empty=True)
    captcha = Captha()
    